import { _decorator, Component, EventTouch, Input, input, Node, UITransform, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('JoyStickmanager')
export class JoyStickmanager extends Component {
    @property(Node)
    body: Node;
    @property(Node)
    stick: Node;

    public input:Vec3;
    private defaultPos: Vec3;

    protected onLoad(): void {
        this.input=new Vec3(0,0,0);
        if(!this.body || !this.stick){
            console.error("JoyStickmanager: body or stick没找到");
        }
        this.defaultPos = this.body.position;
        
        input.on(Input.EventType.TOUCH_START,this.onTouchStart , this);
        input.on(Input.EventType.TOUCH_MOVE,this.onTouchMove , this);
        input.on(Input.EventType.TOUCH_END,this.onTouchEnd , this);
        input.on(Input.EventType.TOUCH_CANCEL,this.onTouchEnd , this);
    }
    protected onDestroy(): void {
        input.off(Input.EventType.TOUCH_START,this.onTouchStart , this);
        input.off(Input.EventType.TOUCH_MOVE,this.onTouchMove , this);
        input.off(Input.EventType.TOUCH_END,this.onTouchEnd , this);
        input.off(Input.EventType.TOUCH_CANCEL,this.onTouchEnd , this);
    }
    onTouchStart(event: EventTouch) {
        console.log("touch start");
        console.log(event.getUILocation());

        let pos = event.getUILocation();
        this.body.setWorldPosition(new Vec3(pos.x,pos.y,0));
        this.stick.setPosition(0,0,0);
        this.input=new Vec3(0,0,0);
    }
    onTouchMove(event: EventTouch) {
        console.log("touch move");
        let clickPos = new Vec3(event.getUILocation().x,event.getUILocation().y,0);
        let currentPos=this.body.getWorldPosition().clone();
        let dic=clickPos.subtract(currentPos);
        if(dic.length()>60){
            dic.normalize();
            this.stick.setPosition(dic.x*60,dic.y*60,0);
        }
        else {
            this.stick.setPosition(dic);
        }
        this.input=dic.clone().normalize();
    }
    onTouchEnd(event: EventTouch) {
        console.log("touch end");
        this.body.setWorldPosition(this.defaultPos);
        this.stick.setPosition(0,0,0);
        this.input=new Vec3(0,0,0);
    }
   
}

